package cn.chanel.mall.service.impl;

import cn.chanel.mall.entity.Category;
import cn.chanel.mall.enums.ResultEnum;
import cn.chanel.mall.exception.MallException;
import cn.chanel.mall.repository.CategoryRepository;
import cn.chanel.mall.service.CategoryService;
import cn.chanel.mall.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryRepository categoryRepository;

    @Override
    public List<Category> getAllCategory() {
        return categoryRepository.findAll();
    }

    @Override
    public Category getCategoryById(String id) {
        final Optional<Category> categoryOpt = categoryRepository.findById(id);
        if(categoryOpt.isEmpty()){
            throw new MallException(ResultEnum.CATEGORY_INF_ERROR);
        }
        return categoryOpt.get();
    }

    @Override
    public void addNewCategory(String name, String describe) {
        Category category = new Category();
        category.setId(KeyUtil.genUniqueKey());
        category.setName(name);
        category.setDescribe(describe);
        val save = categoryRepository.save(category);
        log.info("saveRet = {}", save);
    }
}
